package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.feignclient.SearchServiceClient;
import com.xuecheng.content.feignclient.model.CourseIndex;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.content.service.jobhandler.CoursePublishTask;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: CoursePublishServiceImpl
 * Package: com.xuecheng.content.service.impl
 * Description:
 *
 * @Author Endeavor-ZQB
 * @Create 2023/2/10 19:32
 * @Version 1.0
 */
@Service
@Slf4j
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    CourseBaseInfoService courseBaseInfoService;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CoursePublishMapper coursePublishMapper;



    @Autowired
    TeachplanService teachplanService;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MediaServiceClient mediaServiceClient;

    @Autowired
    SearchServiceClient searchServiceClient;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public CoursePreviewDto getCoursePreviewDto(Long courseId) {
        //获得课程基本信息,课程营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfoDto(courseId);
        if (courseBaseInfo == null){
            log.debug("课程id:{}查询到的课程的基本信息、课程营销信息为空",courseId);
        }

        //获得课程计划的基本信息
        List<TeachplanDto> teachplayTree = teachplanService.findTeachplayTree(courseId);
        if (teachplayTree == null){
            log.debug("课程id:{}查询到的课程计划的基本信息为空",courseId);
        }
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplayTree);

        return coursePreviewDto;
    }

    @Override
    public void commitAudit(Long companyId, Long courseId) {
        //约束校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        //当前审核状态为已提交不允许再次提交
        if (auditStatus.equals("202003")){
            XueChengPlusException.cast("当前为等待审核状态，审核完成可以再次提交。");
        }

        //本机构只允许修改本机构的课程
        if (!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不允许提交其它机构的课程。");
        }

        //课程图片是否填写
        if (StringUtils.isEmpty(courseBase.getPic())){
            XueChengPlusException.cast("提交失败，请上传课程图片");
        }


        //添加课程预发布信息。
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息加上部分营销信息
        CourseBaseInfoDto courseBaseInfo= courseBaseInfoService.getCourseBaseInfoDto(courseId);
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);

        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为JSON
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表中
        coursePublishPre.setMarket(courseMarketJson);

        List<TeachplanDto> teachplayTree = teachplanService.findTeachplayTree(courseId);
        //课程计划是否为空
        if (teachplayTree.size()<=0){
            XueChengPlusException.cast("提交失败，还没有添加课程计划");
        }
        //转为JSON
        String teachplayTreeJson = JSON.toJSONString(teachplayTree);
        //将课程计划信息json数据放入课程预发布表中
        coursePublishPre.setTeachplan(teachplayTreeJson);

        //设置预发布状态，已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());

        //根据id查询课程预发布信息
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreUpdate == null){
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        }else {
            //更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }


        //更新课程基本表course_base课程审核状态为：已提交
       courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    public CoursePublish getCoursePublish(Long courseId){
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);

        return coursePublish ;
    }

    //解决缓存击穿、缓存雪崩问题 ，使用Redisson分布式锁
    public CoursePublish getCoursePublishCache(Long courseId) {

        //查询缓存
        String jsonString = (String) redisTemplate.opsForValue().get("course" + courseId);
        if (StringUtils.isNotEmpty(jsonString)) {
            if (jsonString.equals("null")) {
                return null;
            }
            System.out.println("=================从缓存查=================");
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        else {
            //每门课程设置一个锁
            RLock lock = redissonClient.getLock("coursequerylock" + courseId);
            //获取锁
            lock.lock();
            try {

                jsonString = (String) redisTemplate.opsForValue().get("course" + courseId);
                if (StringUtils.isNotEmpty(jsonString)) {

                    CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
                    return coursePublish;
                }
                System.out.println("从数据库查询...");

                //从数据库查询
                CoursePublish coursePublish = getCoursePublish(courseId);
//            if (coursePublish != null){ //解决缓存穿透，查询一个不存在的数据仍然将null存入缓存
                redisTemplate.opsForValue().set("course" + courseId, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS);
//            }
                return coursePublish;
            }finally {
                //释放锁
                lock.unlock();
            }
        }

    }

    //使用同步锁解决缓存击穿、缓存雪崩问题
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//
//            //查询缓存
//            String jsonString = (String) redisTemplate.opsForValue().get("course" + courseId);
//            if (StringUtils.isNotEmpty(jsonString)) {
//                if (jsonString.equals("null")) {
//                    return null;
//                }
//                System.out.println("=================从缓存查=================");
//                CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//                return coursePublish;
//            }
//            else {
//                synchronized (this) {
//                     jsonString = (String) redisTemplate.opsForValue().get("course" + courseId);
//                    if (StringUtils.isNotEmpty(jsonString)) {
//
//                        CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//                        return coursePublish;
//                    }
//                    System.out.println("从数据库查询...");
//                    //从数据库查询
//                    CoursePublish coursePublish = getCoursePublish(courseId);
////            if (coursePublish != null){ //解决缓存穿透，查询一个不存在的数据仍然将null存入缓存
//                    redisTemplate.opsForValue().set("course" + courseId, JSON.toJSONString(coursePublish), 300 , TimeUnit.SECONDS);
////            }
//                    return coursePublish;
//                }
//            }
//
//    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {
        //约束校验
        //查询课程预发布
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            XueChengPlusException.cast("请先提交课程审核，审核通过才可以发布");
        }
        //本机构只允许修改本机构的课程
        if (!coursePublishPre.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不允许提交其它机构的课程。");
        }

        //根据课程审核状态判断课程是否可以发布
        if (!coursePublishPre.getStatus().equals("202004")){
            XueChengPlusException.cast("操作失败，课程审核通过方可发布。");
        }


        //保存课程发布信息
        saveCoursePublish(courseId);

        //保存消息表
        saveCoursePublishMessage(courseId);


        //删除课程预发布表的对应记录。
        coursePublishPreMapper.deleteById(courseId);

    }

    @Override
    public void courseOffline(Long companyId, Long courseId) {
        //查询课程发布表的一条记录
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        //约束校验
        if (coursePublish == null){
            XueChengPlusException.cast("课程发布表中查询不到该记录");
        }
        if (!companyId.equals(coursePublish.getCompanyId())){
            XueChengPlusException.cast("只允许操作本机构的课程");
        }

        coursePublish.setCompanyId(companyId);
        coursePublish.setCreateDate(LocalDateTime.now());
        coursePublish.setOnlineDate(null);
        coursePublish.setOfflineDate(LocalDateTime.now());
        coursePublish.setStatus("203003");
        coursePublishMapper.updateById(coursePublish);

        //获取课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            XueChengPlusException.cast("该课程信息不存在");
        }
        //修改课程的审核状态和发布状态
        courseBase.setAuditStatus("202002"); //未提交
        courseBase.setStatus("203003");  //下线
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseMapper.updateById(courseBase);

    }

    @Override
    public File generateCourseHtml(Long courseId) {

        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = getCoursePreviewDto(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            File htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
            return htmlFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String result = mediaServiceClient.upload(multipartFile, "course", courseId+".html");
        if (result == null){
            XueChengPlusException.cast("远程调用失败");
        }
    }

    @Override
    public Boolean saveCourseIndex(long courseId) {
        //取出课程发布信息
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        //拷贝至课程索引对象
        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish,courseIndex);
        //远程调用搜索服务api添加课程信息到索引
        Boolean add = searchServiceClient.add(courseIndex);
        if(!add){
            XueChengPlusException.cast("添加索引失败");
        }
        return add;
    }

    /**
     * 保存课程发布信息
     * @param courseId 课程id
     */
    private void saveCoursePublish(Long courseId){
//        向课程发布表course_publish插入一条记录，如果存在则更新，发布状态为：已发布。
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            XueChengPlusException.cast("课程预发布数据为空");
        }
        CoursePublish coursePublish = new CoursePublish();
        coursePublish.setStatus("203002");
        coursePublish.setOnlineDate(LocalDateTime.now());
        BeanUtils.copyProperties(coursePublishPre,coursePublish);

        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if (coursePublishUpdate == null){
            //添加到课程发布表
            coursePublishMapper.insert(coursePublish);
        }else {
            //更新
            coursePublishMapper.updateById(coursePublish);
        }

        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * 保存消息表记录
     * @param courseId
     */
    private void saveCoursePublishMessage(Long courseId) {

        MqMessage mqMessage = mqMessageService.addMessage(CoursePublishTask.MESSAGE_TYPE, String.valueOf(courseId), null, null);

        if (mqMessage == null){
            XueChengPlusException.cast("添加消息记录失败");
        }
    }
}
